<template>
  <el-dialog
    title="批量导入题目"
    :visible.sync="visible"
    width="60%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="活动" prop="collId">
        <coll-select v-model="formData.collId" placeholder="请选择活动" style="width: 360px;"/>
      </el-form-item>
      
      <el-form-item label="题目数据" prop="jsonContent">
        <el-alert
          title="请输入JSON格式的题目数据"
          type="info"
          :closable="false"
          show-icon
          class="mb-2"
        />
        <el-card class="example-card mb-3" shadow="never">
          <pre class="json-example">
[
  {
    "title": "一周有几天？",
    "questionType": 1,  // 1:单选题, 2:多选题, 3:填空题, 4:简答题
    "score": 5,
    "options": [
      {"num": "A", "content": "5天", "isCorrect": false},
      {"num": "B", "content": "6天", "isCorrect": false},
      {"num": "C", "content": "7天", "isCorrect": true},
      {"num": "D", "content": "8天", "isCorrect": false}
    ]
  },
  {
    "title": "小明今年8岁，爸爸的年龄是小明的4倍，爸爸今年______岁。",
    "questionType": 3,
    "score": 5,
    "answer": "32"
  }
]</pre>
        </el-card>
        
        <el-input
          type="textarea"
          v-model="formData.jsonContent"
          :rows="10"
          placeholder="请输入JSON格式的题目数据"
        />
      </el-form-item>
    </el-form>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">导 入</el-button>
    </span>
  </el-dialog>
</template>

<script>
import api from '@/common/api';
import CollSelect from "@/components/admin/ItechCollSelect.vue";

export default {
  name: 'ImportDialog',
  components: {
    CollSelect
  },
  data() {
    return {
      visible: false,
      loading: false,
      formData: {
        collId: '',
        jsonContent: ''
      },
      rules: {
        collId: [
          { required: true, message: '请选择活动', trigger: 'change' }
        ],
        jsonContent: [
          { required: true, message: '请输入JSON数据', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    open({collId}) {
      this.visible = true;
      this.formData = {
        collId: collId || '',
        jsonContent: ''
      };
      // 在下一个事件循环中重置表单验证
      this.$nextTick(() => {
        this.$refs.formRef?.resetFields();
      });
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        
        try {
          // 验证JSON格式
          console.log('this.formData.jsonContent is ', this.formData.jsonContent);
          const jsonData = JSON.parse(this.formData.jsonContent);
          console.log('jsonData is ', jsonData);
          if (!Array.isArray(jsonData)) {
            this.$message.error('JSON数据必须是数组格式');
            return;
          }
          
          this.loading = true;
          await api.admin_importItechCollQuestions({
            collId: this.formData.collId,
            questions: jsonData
          });
          
          this.$message.success('导入成功');
          this.visible = false;
          this.$emit('success');
        } catch (error) {
          if (error instanceof SyntaxError) {
            this.$message.error('JSON格式错误，请检查输入');
          } else {
            this.$message.error('导入失败：' + (error.message || '未知错误'));
          }
        } finally {
          this.loading = false;
        }
      });
    }
  }
};
</script>

<style scoped>
.example-card {
  background-color: #f8f8f8;
  border: 1px dashed #dcdfe6;
}

.json-example {
  margin: 0;
  color: #606266;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-3 {
  margin-bottom: 16px;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
}
</style>
